/**
 * 夜间行车分析
 */
$(function(){
	NightDrivingAna.init();
});

var NightDrivingAna = {
	param: {},
init: function(){
	var me = this;
	me.myChart=null;
	me.initQueryTime();
	me.initEmptyVehicleList();
	me.initVehicleUnitList();
	me.barChart = me.initBarChart();
	var startTime=$("#inputStartDate").val();
   	var endTime=$("#inputEndDate").val();
	me.loadTableTitle();
	me.queryTable();
	me.initEvent();
},

initEvent: function(){
	var me = this;	
	$("#queryBtn").click(function(){
		me.queryBarChartData();
	});
	$("#exportExcel").click(function(){
		me.exportTable();
	});
	$("#chosevech").select2();
},

initVehicleUnitList:function(){
	var me = this;
	
	$("#selectVehicleUnitSel").select2({
        theme: "default",
        allowClear: true,
        placeholder: "全部车辆",
        ajax:{
            url:appCtx + "base/report/RegionalStatistics/getAuthCar.html",
            dataType:"json",
            delay:250,
            data:function(params){
                return {
                    name: params.term,
                    page: params.page || 1
                };
            },
            cache:true,
            processResults: function (res, params) {
		    	if(res){
		    		var options = [];
		    		var option = {"id":" ", "text":"全部车辆"};
		    		options.push(option);
    				$.each(res,function(index,obj) {
    					var option = {"id":obj.vehicle_no+"_"+obj.vehicle_color, "text":obj.vehicle_no};
	                    options.push(option);
    				});
	                return {
	                	results: options,
	                    pagination: {
	                        more:false
	                    }
	                };
		    	}
            },
            escapeMarkup: function (markup) { return markup; },
            minimumInputLength: 1
        }
    });

},

initEmptyVehicleList: function(){
	$("#selectVehicleSel").select2({
		theme: "default",
	        allowClear: true,
	        placeholder: "全部业户",
	        ajax:{
	            url:appCtx + "base/report/NoCardCounting/queryEnterAndPlatByRole.html",
	            dataType:"json",
	            delay:250,
	           async : true,
	            data:function(params){
	                return {
	                    name: params.term,
	                    page: params.page || 1
	                };
	            },
	            cache:true,
	            processResults: function (res, params) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部业户"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
	    					var option = {"id":obj.entId, "text":obj.entName,"value":obj.entName};
 	                    options.push(option);
	    				});
 	                return {
 	                	results: options,
 	                    pagination: {
 	                        more:false
 	                    }
 	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1
	        }
	})
	/*var me = this;
	$.ajax({
		type : 'post',
		url : appCtx + "base/report/NoCardCounting/queryEnterAndPlatByRole.html",
		cache : false,
		dataType : "JSON",
		success : function(data) {
				var selectStry="<option value=''>请选择业户</option>";
				$.each(data,function(index,f){
					selectStry+="<option value='"+f.entName+"'>"+f.entName+"</option>";
				});
				$('#selectVehicleSel').html(selectStry);		
				$("#selectVehicleSel").select2();
				$("#selectVehicleSel").change(function(){
				});
			}
	});*/

},
    
initBarChart: function(){
	var me = this;
	//计算显示的柱子数
	var percent = 100;

	option = {
	    color: ['#3398DB'],
	    tooltip : {
	        trigger: 'axis',
	        show: true,
	        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
	        	show: false,
	            type : 'none'        // 默认为直线，可选为：'line' | 'shadow'
	        },
	        formatter:function(a){
	        	if(a[0].name==''){
	        		return;
	        	}
	        	var relVal = "";
	        	relVal = a[0].name+"："+a[0].value+"次";
	        	return relVal;
	        }
	    },
	    grid: {
	        left: '7px',
	        top:'10%',
	        right: '10px',
	        containLabel: true
	    },
	    xAxis : [
	        {
	            type : 'category',
	            data : [],
	            axisTick: {
	                alignWithLabel: true
	            },
	            axisLabel:{
	            	textStyle: {
                        fontSize: 10
                    }
	            }
	        }
	    ],
	    yAxis : [
	        {
	            type : 'value',
	            show: true,    //显示纵轴false-不显示，true-显示 
	            min: 0,
		    	minInterval: 1,
		    	axisLabel: {
                      formatter: function (value, index) {
                    	  if (value >= 1 || value == 0) {
                          	if (value%1 === 0) {
                          		return value;
                          	}
                          }
                        }
                 },
	            name: '单位【次】'
	        }
	    ],
	    series : [
	        {
	            name:'业户统计',
	            type:'bar',
	            barMaxWidth: '45px',
	            itemStyle: {
	                normal: {
	                    label : {
	                        show: true, position: 'insideTop' //柱状图顶部显示数字
	                    }
	                }
	            },
	            data:[]
	        }
	    ],
	    dataZoom: [{
	        type: 'inside',
	        start: 0,
	        end: percent
	    }, {
	        start: 0,
	        end: percent,
	        fillerColor:'#A3E1A3',
	        handleColor:'#83A7D1',
	        showDetail:false
	    }]
	};
        var myChart = echarts.init(document.getElementById('barChart'));
        myChart.setOption(option);
        window.onresize = myChart.resize;
        myChart.on('click', function(param){
        	me.queryTable(param.name);
        });     
        return {
        	refash : function(option){
                myChart.setOption(option);
        	},
        	option : option,
        	barChartDom : myChart
        };        
},

queryBarChartData: function(){
  var startTime=$("#inputStartDate").val();
  var endTime = $("#inputEndDate").val();
	var  chose = $("#chosevech").val();
	var vehicle = null;
	var enterprise = null;
	if(chose==0){ //车辆
		vehicle = $("#selectVehicleUnitSel").val();
	}else if(chose==1){	//业户	
		enterprise = $("#selectVehicleSel").val();
	}
	var me = this;
	$.ajax({
		type : 'post',
		url : appCtx+"base/report/NoCardCounting/queryNoCardCounting.html",
		data:{
			   enterpirseName:enterprise,
			   vehicleId:vehicle,
			   startTime:startTime,
			   endTime:endTime
			 },
		cache : false,
		dataType : "JSON",
		success : function(data) {
			var option = me.barChart.option;
			option.xAxis[0].data = data.xAxisData;// ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
			option.series[0].data = data.series; //[10, 52, 200, 334, 390, 330, 220];
			me.barChart.refash(option);
			me.vehicleIdList = data.xAxisData;
			//默认展示第一个的列表
		if(vehicle==null||vehicle==''){
			if(enterprise==null||enterprise==''){
				me.queryTable(data.xAxisData[0],null);
			}else if(enterprise!=null&&enterprise==''){
				me.queryTable(enterprise,null);
			}
		}else{
				me.queryTable(null,vehicle);
			}
		}
	});
},

    getColumn:function(){
    	var me = this;
    	return [/*{
            display : '序号',
            name : 'index',
            width : 5,
            sortable : false,
            align : 'center'
        },*/{
            display : '业户',
            name : 'enterprise_name',
            width : 25,
            sortable : false,
            align : 'center',
            showTitle : 'enterprise_name'
        },{
            display : '车牌号',
            name : 'vehicle_no',
            width : 8,
            sortable : false,
            align : 'center',
            showTitle : 'vehicle_no'
        },{
            display : '颜色',
            name : 'vehicle_color',
            width : 5,
            sortable : false,
            align : 'center',
            showTitle : 'vehicle_color',
            paramcolnames:['vehicle_color'],
            handlefunction:me.getColor
        },{
            display : '驶出区域时间',
            name : 'gps_time',
            width : 16,
            sortable : false,
            align : 'center',
            showTitle : 'gps_time',
            paramcolnames:['gps_time'],
            handlefunction:function(gps_time){
        		return global.getTime(new Date(Number(gps_time)));;
            }
        },{
            display : '驶出区域位置',
            name : 'outLocation',
            width : 34,
            sortable : false,
            align : 'left',
            showTitle : 'outLocation',
        },{
        	display : '操作',
            name : 'Handler',
            width : 7,
            sortable : false,
            align : 'center',
            paramcolnames:['vehicle_no'],
            handlefunction:function(vehicle_no){
        		var handleStr = '<div style="padding:0px;float:left;width:35px;height:19px;cursor:pointer;"><img id="'+vehicle_no.substring(1,7)+'" name="trackPlayBtn" src="'+global.url.domain+'gps-web/resources/images/track.png" title="定位">定位<div>';		
        		return handleStr;
            }
        }]
    },
    getColor :function(vehicleColor){
    	var handleStr
    	if(vehicleColor=='1'){
    		handleStr='蓝色';
    	}else if(vehicleColor=='2'){
    		handleStr='黄色';
    	}else if(vehicleColor=='3'){
    		handleStr='黑色';
    	}else if(vehicleColor=='4'){
    		handleStr='白色';
    	}else if(vehicleColor=='9'){
    		handleStr='其他';
    	}
		return handleStr;
    },
    loadTableTitle:function(){
    	$("#objTable").flexigrid({
            dataType : 'json',
            colModel :this.getColumn() ,
            usepager : true,// 是否分页，默认为true。
            singleSelect:true,
			sortname : "id",// 第一次加载数据时排序列
			sortorder : "desc",// 第一次加载数据时排序类型
            height:308,
			useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
			rp : 10,// 每页记录数，默认为10
            widthType:'%',
	        width:$('.detail-report').width(),
	       });	 
    },


    initQueryTime:function(){
        var todayDate = new Date();
        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
        //$("#inputEndDate").val(todayDateStr);
        	
        var beforeDate = new Date(todayDate-86400000*1); //前一天
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.length == 1) {
	        dd = '0' + dd;
	    }
        $("#inputStartDate").val(yyyy + '-' + mm + '-' + dd);
        $("#inputEndDate").val(yyyy + '-' + mm + '-' + dd);
      },
 queryTable: function(enterprise_name,vehicleId){
  var startTime=$("#inputStartDate").val();
  var endTime = $("#inputEndDate").val();
	  // 查询参数
	  var params = [{
		name : 'startTime',
		value : startTime
	  },{
		name : 'endTime',
		value : endTime
	  },{
		name : 'enterpirseName',
		value : enterprise_name
	  },{
		name : 'vehicleId',
		value : vehicleId
	  }];
  $("#objTable").flexOptions({
		url:appCtx+"base/report/NoCardCounting/queryTables.html",
		newp : 1,// 设置起始页
		params : params
	// 设置查询参数
  }).flexReload();// 重新加载
},

exportTable:function(){
	var options = $("#objTable").getOptions();
	//总记录数
	var total = options.total;
	if(total==0){
		global.ajaxLoading.pop("无数据",false,1000);
		return;
	}
	var pages = options.pages;
	//设置默认的开始结束页
	$("#StartPageIndex").val(1);
	$("#EndPageIndex").val(pages);
    $("#exportTitle").html("旅游无包车牌进出区域导出");
	$("#exportModal").modal('show');
},
exportExcel : function(){
	var me = this;
	$("#exportModal").modal('hide');
	var header1 = JSON.stringify(me.getColumn());
	var header2 = JSON.parse(header1);
	
	var  chose = $("#chosevech").val();
	var vehicle = null;
	var enterprise = null;
	if(chosevech==0){ //车辆
		vehicle = $("#selectVehicleUnitSel").val();
	}else if(chosevech==1){	//业户	
		enterprise = $("#selectVehicleSel").val();
	}
	//开始页数
	var StartPage=$("#StartPageIndex").val();
	//结束页数
	var EndPage=$("#EndPageIndex").val();
	var options = $("#objTable").getOptions();
	//总记录数
	var total = options.total;
	var pagesize = options.rp;
	var headerWidth = $('.detail-report').width()+500;
	for(var i=0;i<header2.length;i++){
		header2[i].width = Math.ceil(headerWidth / 100 * header2[i].width);
	}
	header2.splice(header2.length-1,1);
	var header3 = JSON.stringify(header2);
	 var imageUrl = me.barChart.barChartDom.getDataURL({
		type: 'png',
	    pixelRatio: 1
	});  
	//表头
	var colModelList=new Array();
	colModelList.push(header3);
	var colModel= $.toJSON(colModelList);
	
	//图片
	var imgsrcList=new Array();
	imgsrcList.push(imageUrl);
	var imgsrc= $.toJSON(imgsrcList);
		
	var param =  {
			startTime:$("#inputStartDate").val()+" 00:00；00",
			endTime: $("#inputEndDate").val()+" 23:59:59",
			vehicleId:vehicle,
			enterprise_name:enterprise,
			colModel:colModel,
			StartPage:StartPage,
			EndPage:EndPage,
			pagesize:pagesize,
			title:"旅游无包车牌进出区域导出",
			imgsrc:imgsrc
	};
	post(appCtx+"base/report/NoCardCounting/exportNoCardCounting.html",param);
},

};
function chosevech(){
	var  chose = $("#chosevech").val();
	if(chose==0){
		$("#chosecar").attr("style","background: #1d63a9;")
		$("#choseenterpirse").attr("style","background: #dfdfdf");
		$("#vehicleSelDiv").hide();	
		$("#UnitSel").show();
		enterprise=''
	}
	if(chose==1){		
		$("#choseenterpirse").attr("style","background: #1d63a9;")
		$("#chosecar").attr("style","background: #dfdfdf");
		$("#UnitSel").hide();
		$("#vehicleSelDiv").show();
		vehicle=''
	}
};